import { Outlet, history, useAppData, useLocation } from "@umijs/max";
import { Layout, Menu } from "antd";
import cloneDeep from "lodash/cloneDeep";
import { useMemo } from "react";
import styles from "./BasicLayout.less";
import Header from "./_components/Header";

const { Sider } = Layout;

const handleMenu = (item) => {
  return {
    key: item?.path,
    label: <span>{item?.name}</span>,
    children: item?.children,
  };
};
const handleRoute = (arr) => {
  return arr?.reduce?.((result, item) => {
    item?.routes?.forEach?.((items) => {
      if (items?.routes) {
        items.children = handleRoute([items]);
      }
      result.push(handleMenu(items));
    });
    return result;
  }, []);
};

export default () => {
  const { clientRoutes = [], routes: router } = useAppData();
  const { pathname } = useLocation();

  const routes = useMemo(() => {
    const route = cloneDeep(clientRoutes);
    return handleRoute(route); //根据路由生成菜单
  }, [clientRoutes]);
  const { openKey, nowRoute } = useMemo(() => {
    const routesArr = Object.values(router);
    const nowRoute = routesArr?.find?.((item) => item.path === pathname); //当前路由信息
    const parentRoute = routesArr?.find?.(
      (item) => nowRoute.parentId === item.id
    ); //当前路由的父路由
    return {
      openKey: parentRoute?.path,
      nowRoute,
    };
  }, [pathname, router]);

  return (
    <div className={styles.container}>
      <Layout className={styles.content}>
        <Layout className={styles.headerContainer}>
          <Header />
        </Layout>
        <Layout className={styles.bottomContainer}>
          {!nowRoute?.hideMenu && (
            <Sider width={208}>
              <Menu
                className={styles.leftSider}
                mode="inline"
                defaultSelectedKeys={[pathname || ""]}
                selectedKeys={[pathname]}
                defaultOpenKeys={[openKey]}
                onSelect={(e) => {
                  history.push(e.key);
                }}
                items={routes || []}
              />
            </Sider>
          )}

          <Layout className={styles.contentContainer}>
            <Outlet />
          </Layout>
        </Layout>
      </Layout>
    </div>
  );
};
